package com.example.coursedesign.ui.home;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.dao.mRemindDao;
import com.example.coursedesign.ui.home.entity.mRemind;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class addRemind extends AppCompatActivity implements DosageUnitPickerBottomSheet.OnUnitSelectedListener,TimeUnitPickerBottomSheet.OnUnitsSelectedListener, CurrentDosageUnitPicker.OnUnitSelectedListener,RemindTimeUnitPicker.OnUnitsSelectedListener {
    private static final String TAG = "mysql-coursedesign-addRemind";
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int REQUEST_PERMISSIONS = 2;
    private EditText editText_drugName;
    private EditText editText_requiredDosage;
    private EditText editText_currentDosage;
    private EditText editText_note;
    private EditText editText_timeToTake;
    private EditText editText_reminderTime;
    private Button button_save;
    private Button button_addDrugImage;
    private ImageButton imageButton_removeImage;
    private ImageView imageView_drugImage;
    private byte[] imageBytes;
    private mRemind remind;
    private String lastSelectedUnit = ""; // 保存上次选中的单位
    private String lastSelectedUnitLeft = ""; // 默认为空字符串
    private String lastSelectedUnitRight = ""; // 默认为空字符串
    private static final String[] unitsLeft = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
    private static final String[] unitsRight = generateMinuteArray(); // 动态生成分钟数组
    // 动态生成 00 到 59 的分钟数组
    private static String[] generateMinuteArray() {
        String[] minutes = new String[60];
        for (int i = 0; i < 60; i++) {
            minutes[i] = String.format("%02d", i); // 确保是两位数格式，如 "01", "02", ..., "59"
        }
        return minutes;
    }
        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_remind);
        getSupportActionBar().setTitle("添加提醒");

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
        }

        initViews();

        Intent intent = getIntent();
        remind = intent.getParcelableExtra("remind");

        if (remind != null) {
            populateExistingData();
        }

        setupButtonClickListeners();
    }

    private void initViews() {
        editText_drugName = findViewById(R.id.editText_drugName);
        editText_requiredDosage = findViewById(R.id.editText_requiredDosage);
        editText_currentDosage = findViewById(R.id.editText_currentDosage);
        editText_note = findViewById(R.id.editText_note);
        button_save = findViewById(R.id.button_save);
        button_addDrugImage = findViewById(R.id.button_add_image);
        editText_timeToTake = findViewById(R.id.editText_timeToTake);
        editText_reminderTime = findViewById(R.id.editText_reminderTime);
        imageView_drugImage = findViewById(R.id.image_view);
        imageButton_removeImage = findViewById(R.id.button_remove_image);
        ImageButton imageButton_right = findViewById(R.id.imageButton_right); // 获取ImageButton
        ImageButton time_imageButton_right = findViewById(R.id.time_imageButton_right);
        ImageButton correntMedicine_right = findViewById(R.id.correntMedicine_right);
        ImageButton remindTime_right = findViewById(R.id.remindTime_right);

        imageButton_right.setOnClickListener(v -> {
            DosageUnitPickerBottomSheet bottomSheet = new DosageUnitPickerBottomSheet();
            showDosageUnitPicker(bottomSheet);
        });
        correntMedicine_right.setOnClickListener(v -> {
           CurrentDosageUnitPicker bottomSheet = new CurrentDosageUnitPicker();
            showCurrentDosageUnitPicker(bottomSheet);
        });
        time_imageButton_right.setOnClickListener(v -> {
            TimeUnitPickerBottomSheet bottomSheet = new TimeUnitPickerBottomSheet();
            showTimeUnitPicker(bottomSheet);
        });
        remindTime_right.setOnClickListener(v -> {
            RemindTimeUnitPicker bottomSheet = new RemindTimeUnitPicker();
            showRemindTimeUnitPicker(bottomSheet);
        });
    }
    //剩余药量
    private void showCurrentDosageUnitPicker(CurrentDosageUnitPicker bottomSheet) {
        Bundle bundle = new Bundle();
        bundle.putInt("defaultUnitIndex", getCurrentLastSelectedUnitIndex());
        bottomSheet.setArguments(bundle);
        bottomSheet.show(getSupportFragmentManager(), "DosageUnitPicker");
    }

    private int getCurrentLastSelectedUnitIndex() {
        String[] units = CurrentDosageUnitPicker.getUnits(); // 使用公共方法获取 units 数组
        for (int i = 0; i < units.length; i++) {
            if (units[i].equals(lastSelectedUnit)) {
                return i;
            }
        }
        return 0; // 默认索引
    }
    //服用药量
    private void showDosageUnitPicker(DosageUnitPickerBottomSheet bottomSheet) {
        Bundle bundle = new Bundle();
        bundle.putInt("defaultUnitIndex", getLastSelectedUnitIndex());
        bottomSheet.setArguments(bundle);
        bottomSheet.show(getSupportFragmentManager(), "DosageUnitPicker");
    }

    private int getLastSelectedUnitIndex() {
        String[] units = DosageUnitPickerBottomSheet.getUnits(); // 使用公共方法获取 units 数组
        for (int i = 0; i < units.length; i++) {
            if (units[i].equals(lastSelectedUnit)) {
                return i;
            }
        }
        return 0; // 默认索引
    }
    //服药时间
    private void showTimeUnitPicker(TimeUnitPickerBottomSheet bottomSheet) {
        Bundle bundle = new Bundle();
        bundle.putInt("defaultUnitIndexLeft", getTimeLastSelectedUnitIndex(unitsLeft, lastSelectedUnitLeft));
        bundle.putInt("defaultUnitIndexRight", getTimeLastSelectedUnitIndex(unitsRight, lastSelectedUnitRight));
        bottomSheet.setArguments(bundle);
        bottomSheet.show(getSupportFragmentManager(), "TimeUnitPicker");
    }

    private int getTimeLastSelectedUnitIndex(String[] units, String lastSelectedUnit) {
        for (int i = 0; i < units.length; i++) {
            if (units[i].equals(lastSelectedUnit)) {
                return i;
            }
        }
        return 0; // 默认索引
    }
    //提醒时间
    private void showRemindTimeUnitPicker(RemindTimeUnitPicker bottomSheet) {
        Bundle bundle = new Bundle();
        bundle.putInt("defaultUnitIndexLeft", getRemindTimeLastSelectedUnitIndex(unitsLeft, lastSelectedUnitLeft));
        bundle.putInt("defaultUnitIndexRight", getRemindTimeLastSelectedUnitIndex(unitsRight, lastSelectedUnitRight));
        bottomSheet.setArguments(bundle);
        bottomSheet.show(getSupportFragmentManager(), "TimeUnitPicker");
    }

    private int getRemindTimeLastSelectedUnitIndex(String[] units, String lastSelectedUnit) {
        for (int i = 0; i < units.length; i++) {
            if (units[i].equals(lastSelectedUnit)) {
                return i;
            }
        }
        return 0; // 默认索引
    }


    private void populateExistingData() {

        // 首先检查 remind 是否为 null
        if (remind == null) {
            return;
        }
        editText_drugName.setText(remind.getName());
        editText_requiredDosage.setText(remind.getNumber());
        editText_currentDosage.setText(remind.getCurrentNumber());
        editText_note.setText(remind.getDetail());
        editText_timeToTake.setText(remind.getTime());
        editText_reminderTime.setText(remind.getRemindTime());

        // 安全地分割并获取Base64编码部分
        String base64Image = "";
        if (remind.getPicture() != null && !remind.getPicture().isEmpty()) {
            try {
                if (remind.getPicture().contains(",")) {
                    base64Image = remind.getPicture().split(",", 2)[1];
                } else {
                    base64Image = remind.getPicture();
                }
                byte[] imageBytes = Base64.decode(base64Image, Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                imageView_drugImage.setImageBitmap(bitmap);
                imageView_drugImage.setVisibility(View.VISIBLE); // 确保ImageView是可见的
                imageButton_removeImage.setVisibility(View.VISIBLE);
                button_addDrugImage.setText("重新上传");
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                Toast.makeText(this, "图片数据无效", Toast.LENGTH_SHORT).show();
                imageView_drugImage.setVisibility(View.GONE); // 如果加载失败，隐藏ImageView
                imageButton_removeImage.setVisibility(View.GONE);
                button_addDrugImage.setText("+上传药品图");
            }
        } else {
            imageView_drugImage.setVisibility(View.GONE); // 没有图片时隐藏ImageView
            imageButton_removeImage.setVisibility(View.GONE);
            button_addDrugImage.setText("+上传药品图");
        }
    }

    private void setupButtonClickListeners() {

        button_save.setOnClickListener(v -> {

            saveRemind();
        });

        button_addDrugImage.setOnClickListener(v -> {

            if (ContextCompat.checkSelfPermission(addRemind.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(addRemind.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS);

            } else {
                openFileChooser();
            }
        });

        imageButton_removeImage.setOnClickListener(v -> {
            Log.d("addRemind", "setupButtonClickListeners: Remove image button clicked");
            imageView_drugImage.setVisibility(View.GONE);
            imageButton_removeImage.setVisibility(View.GONE);
            button_addDrugImage.setText("+上传药品图");
            imageBytes = null;
        });
    }

    private void openFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri uri = data.getData();
            try (InputStream inputStream = getContentResolver().openInputStream(uri)) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                imageView_drugImage.setImageBitmap(bitmap);
                imageView_drugImage.setVisibility(View.VISIBLE);
                imageButton_removeImage.setVisibility(View.VISIBLE);
                button_addDrugImage.setText("重新上传");

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
                imageBytes = byteArrayOutputStream.toByteArray();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFileChooser();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void saveRemind() {
        // 获取编辑框中的内容并去除首尾空格
        String drugName = editText_drugName.getText().toString().trim();
        String requiredDosage = editText_requiredDosage.getText().toString().trim();
        String currentDosage = editText_currentDosage.getText().toString().trim();
        String note = editText_note.getText().toString().trim();
        String timeToTake = editText_timeToTake.getText().toString().trim();
        String reminderTime = editText_reminderTime.getText().toString().trim();

        // 验证必填字段
        if (drugName.isEmpty() || requiredDosage.isEmpty() || currentDosage.isEmpty()) {
            Toast.makeText(this, "药物名称、所需剂量和当前剂量是必填项", Toast.LENGTH_SHORT).show();
            return;
        }

        // 初始化或更新提醒对象
        if (remind == null) {
            remind = new mRemind();
        }

        // 设置提醒对象属性
        remind.setName(drugName);
        remind.setNumber(requiredDosage);
        remind.setTime(timeToTake);
        remind.setCurrentNumber(currentDosage);
        remind.setRemindTime(reminderTime);
        remind.setDetail(note);
        remind.setStatus("未服用");

        // 处理图片
        if (imageBytes != null) { // 如果选择了新图片
            String base64Image = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            remind.setPicture("data:image/jpeg;base64," + base64Image);
        } else {
            // 如果没有选择新图片，则保留原图片
            remind.setPicture(remind.getPicture());
        }

        // 创建线程池执行器和主线程处理器
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Handler handler = new Handler(getMainLooper());

        // 执行保存操作
        executor.execute(() -> {
            mRemindDao remindDao = null;
            try {
                remindDao = new mRemindDao();
                if (remind.getId() == 0) {
                    // 新增提醒
                    remind = remindDao.create(remind);
                } else {
                    // 更新提醒
                    boolean isUpdated = remindDao.update(remind);
                    if (!isUpdated) {
                        throw new Exception("更新失败");
                    }
                }

                // 回到主线程更新UI并返回结果
                handler.post(() -> {
                    Toast.makeText(addRemind.this, "保存成功", Toast.LENGTH_SHORT).show();

                    // 发送广播通知列表需要刷新
                    Intent broadcastIntent = new Intent("com.example.coursedesign.UPDATE_REMIND_LIST");
                    sendBroadcast(broadcastIntent);

                    // 将更新后的提醒对象放入 Intent 并设置结果
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("REMIND_ID", remind.getId()); // 只传递ID以避免序列化整个对象
                    setResult(RESULT_OK, resultIntent);

                    finish(); // 结束当前活动
                });

            } catch (Exception e) {
                e.printStackTrace();
                handler.post(() -> Toast.makeText(addRemind.this, "保存失败，请重试：" + e.getMessage(), Toast.LENGTH_SHORT).show());
            } finally {
                if (remindDao != null && remindDao instanceof AutoCloseable) {
                    try {
                        ((AutoCloseable) remindDao).close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                // 确保线程池正确关闭
                executor.shutdown();
                try {
                    if (!executor.awaitTermination(800, TimeUnit.MILLISECONDS)) {
                        executor.shutdownNow();
                    }
                } catch (InterruptedException ie) {
                    executor.shutdownNow();
                }
            }
        });
    }
    //服用药量
    @Override
    public void onUnitSelected(String unit) {
        // 更新编辑框内容或执行其他操作
        String currentText = editText_requiredDosage.getText().toString().trim();

        // 清除之前的单位信息
        if (!currentText.isEmpty() && !Character.isDigit(currentText.charAt(currentText.length() - 1))) {
            currentText = currentText.substring(0, currentText.lastIndexOf(" "));
        }
        // 添加新的单位信息
        if (!currentText.endsWith(unit)) {
            editText_requiredDosage.setText(currentText + " " + unit);
            lastSelectedUnit = unit; // 记录最后选中的单位
        }
    }
    //剩余药量
    @Override
    public void onUnitCurrentMedicineSelected(String unit) {
        // 更新编辑框内容或执行其他操作
        String currentMedicineText = editText_currentDosage.getText().toString().trim();

        // 清除之前的单位信息
        if (!currentMedicineText.isEmpty() && !Character.isDigit(currentMedicineText.charAt(currentMedicineText.length() - 1))) {
            currentMedicineText = currentMedicineText.substring(0, currentMedicineText.lastIndexOf(" "));
        }
        // 添加新的单位信息
        if (!currentMedicineText.endsWith(unit)) {
            editText_currentDosage.setText(currentMedicineText + " " + unit);
            lastSelectedUnit = unit; // 记录最后选中的单位
        }
    }
    //服药时间
    @Override
    public void onTimeUnitSelected(String unitLeft, String unitRight) {
        // 更新编辑框内容或执行其他操作
        String currentTimeText = editText_timeToTake.getText().toString().trim();

        if (!currentTimeText.isEmpty() && !Character.isDigit(currentTimeText.charAt(currentTimeText.length() - 1))) {
            int lastSpaceIndex = currentTimeText.lastIndexOf(" ");
            if (lastSpaceIndex != -1) {
                currentTimeText = currentTimeText.substring(0, lastSpaceIndex);
            } else {
                currentTimeText = ""; // 如果没有空格，则清空文本
            }
        }

        // 确保不重复添加相同的单位
        if (!currentTimeText.endsWith(unitLeft + " " + unitRight)) {
            editText_timeToTake.setText(currentTimeText + " " + unitLeft + ":" + unitRight);
            lastSelectedUnitLeft = unitLeft; // 记录最后选中的左边单位
            lastSelectedUnitRight = unitRight; // 记录最后选中的右边单位
        }
    }
    //提醒时间
    @Override
    public void onRemindTimeUnitSelected(String unitLeft, String unitRight) {
        // 更新编辑框内容或执行其他操作
        String remindTimeText = editText_reminderTime.getText().toString().trim();

        if (!remindTimeText.isEmpty() && !Character.isDigit(remindTimeText.charAt(remindTimeText.length() - 1))) {
            int lastSpaceIndex = remindTimeText.lastIndexOf(" ");
            if (lastSpaceIndex != -1) {
                remindTimeText = remindTimeText.substring(0, lastSpaceIndex);
            } else {
                remindTimeText = ""; // 如果没有空格，则清空文本
            }
        }

        // 确保不重复添加相同的单位
        if (!remindTimeText.endsWith(unitLeft + " " + unitRight)) {
            editText_reminderTime.setText(remindTimeText + " " + unitLeft + ":" + unitRight);
            lastSelectedUnitLeft = unitLeft; // 记录最后选中的左边单位
            lastSelectedUnitRight = unitRight; // 记录最后选中的右边单位
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        setResult(RESULT_OK);
        finish();
        return true;
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }

}